//每隔一分钟检查一次是否在线
function onlineCheck(){
	//现在的时间
	var date = new Date();
	var time = date.getTime()/1000;
	$("div.timestamp").each(function(){
		//该房间最近一条数据的时间
		var time1 = parseInt($(this).text());
		if(time-time1>30){
			$(this).prev("div.value").text("--");
			if($(this).prev("div.value").attr("title")=='PM2.5'){
				$(this).prev("div.value").css("color","#333");
				$(this).parent().attr("class","room roomOffline");
			}
		}
	});
}
function refreshData(){
	var usr = getSelUsername();
	var uid = getSelUserid();
	$.ajax({
		type:"post",
		url:"/data/getLastDataOfUser.action",
		data:{usrName:usr,type:'all'},
		success:function(resp){
		    showData(resp);
		}
	});
}
function showData(resp){
	try{
		var dataArr = JSON.parse(resp);
		if(dataArr && dataArr.length>0){
			for(var i=0;i<dataArr.length;i++){
				var data=dataArr[i];
				putDataToRoom(data);
			}
		}
	}
	catch(e){
		var a=e;
	}
}
function putDataToRoom(data){
	var devId = data.devId;
	var rt = data.roomType;
	var pm25 = data.pm25;
	var jq = data.jq;
	var wd = data.wd;
	var sd = data.sd;
	var co2 = data.co2;
	var tvoc = data.tvoc;
	if (!rt) {
	    rt=63;
	}
	if (0==(rt&1)) {
	    pm25="--";
	}
	if (0==(rt&(1<<1))) {
	    wd="--";
	}
	if (0==(rt&(1<<2))) {
	    sd="--";
	}
	if (0==(rt&(1<<3))) {
	    co2="--";
	}
	if (0==(rt&(1<<4))) {
	    tvoc="--";
	}
	if (0==(rt&(1<<5))) {
	    jq="--";
	}
	if (wd!='--') {
	    wd = wd.toFixed(2)+"℃";
	}
	if (sd!="--") {
	    sd = sd.toFixed(2)+ "%";
	}
	if(co2!='--'){
	    co2+= " ppm";
	}
	if(tvoc!='--'){
	    if (tvoc>0) {
		tvoc += ' ppm';
	    }else{
		tvoc = -tvoc;
		tvoc += ' mg';
	    }
	}
	if(jq!='--'){
		jq += ' mg';
	}
	
	if(pm25=="--"){
		cls="room roomOffline";
	}else{
		var value = pm25;
		if(value>=100){
			value = parseInt(value);
		}else{
			value = Math.round(parseFloat(value)*10)/10;
		}
		pm25 = value;
		if(value<=35){
			cls="room room1";
		}else if(value>35 && value<=75){
			cls="room room2";
		}else if(value>75 && value<=115){
			cls="room room3";
		}else if(value>115 && value<=150){
			cls="room room4";
		}else if(value>150 && value<=250){
			cls="room room5";
		}else if(value>250){
			cls="room room6";
		}else{
			//error
			return;
		}
	}
	$('#nova-room-table').find("div.devId").each(function(){
		if($(this).text()==devId){
			var a = $(this).nextAll("div.pm25").find("div.value[title='PM2.5']");
			if(a){
				$(a).text(pm25);
				if(pm25=="--"){
					$(a).css('color','#333');
				}
				if(cls!=""){
					$(this).parent().attr("class",cls);
				}
			}
			a = $(this).nextAll("div.wendu").find("div.value[title='温度']");
			if(a){
			    $(a).text(wd);
			};
			a = $(this).nextAll("div.shidu").find("div.value[title='湿度']");
			if(a){
			    $(a).text(sd);
			};
			if(bTvoc){
				a = $(this).nextAll("div.tvoc").find("div.value[title='异味指数']");
				if(a){
					$(a).text(tvoc);
				};
			}
			if(bJiaquan){
				a = $(this).nextAll("div.jiaquan").find("div.value[title='甲醛']");
				if(a){
					$(a).text(jq);
				};
			}
			if(bCo2){
				a = $(this).nextAll("div.co2").find("div.value[title='二氧化碳']");
				if(a){
					$(a).text(co2);
				};
			}
		}
	});
}
function addDevAuto(dev){}
function showMsg(msg){
	if(msg==undefined || msg=="" || msg.indexOf("devId")==-1 ||msg.indexOf("hist")!=-1){
		return;
	}
	//msgArr.push(msg);
	setTimeout(function(){addMsg(msg);},200);
}
function procMsg(){
	while(msgArr.length>0){
		addMsg(msgArr.shift());
	}
}
function addMsg(msg){
	var dat = JSON.parse(msg);
	//type:PM2.5,甲醛,二氧化碳,温湿度
	var type = dat.type;
	//devId
	var devId = dat.devId;
	//room
	//var room = dat.room;
	//value
	var value = dat.value;
	//time
	//var time = parseInt(dat.time);
	var time = (new Date().getTime())/1000;
	//classname
	var cls="";
	var clr;
	if(type=="PM2.5"){
		if(value>=100){
			value = parseInt(value);
		}else{
			value = Math.round(parseFloat(value)*10)/10;
		}
		if(value<=35){
			cls="room room1";
		}else if(value>35 && value<=75){
			cls="room room2";
		}else if(value>75 && value<=115){
			cls="room room3";
		}else if(value>115 && value<=150){
			cls="room room4";
		}else if(value>150 && value<=250){
			cls="room room5";
		}else if(value>250){
			cls="room room6";
		}else{
			//error
			return;
		}
	}
	var div = $('#nova-room-table').find("div.devId").each(function(){
		if($(this).text()==devId){
			var a = $(this).nextAll("div.value[title='"+type+"']");
			$(a).text(value);
			//$(this).nextAll("div.value[title='"+type+"']").css("color",clr);
			//$(this).nextAll("div.header").text(room);
			$(a).nextAll("div.timestamp:first").text(time);
			if(cls!=""){
				$(this).parent().attr("class",cls);
			}
		}
	});
}
function clk_data(div){
    var type=$(div).attr('class');
    plotDevId = $(div).siblings("div.devId").text();
   // var uid = getSelUserid();
    //window.open("/plot.html?sn="+plotDevId+"&uid="+uid+"&type="+type);
    window.open(base + "/directToChartPage/" + plotDevId + "-" + type);
}
function click_room(obj){
    plotDevId = $(obj).siblings("div.devId").text();
    //plotDevId=plotDevId.substr(0,4).toUpperCase()+plotDevId.substr(4,4).toUpperCase();
//    plotRoom = $(obj).text();
    //window.open(path+"jsp/plot.jsp?dev="+plotDevId+"&room="+plotRoom);
//    var uid = getSelUserid();
    
    window.open(base + "/directToChartPage/" + plotDevId);
}
function findGroups(){
	$.ajax({
		type:"post",
		url:"/dev/findDevGroupList.action",
		data:{},
		success:function(response){
			if(response.indexOf("!")!=-1){
				alert(response)
			}else{
				showGroups(response);
			}
		}
	});
}
function showGroups(groups){
	var gs = JSON.parse(groups);
	if(gs==null){
		return;
	}else{
		var str="<ul>";
		var total=0;
		for(var i=0;i<gs.length;i++){
			str += "<li onclick='click_group(this)'>";
			str += "<span class='hide'>"+gs[i].id+"</span>";
			//str += "<span class='hide'>-1</span>";
			str += "<span class='groupNm'>"+gs[i].name+"</span>";
			str += "<span >["+gs[i].size+"]</span>";
			str += "</li>";
			total += parseInt(gs[i].size);
		}
		//str += "<li onclick='click_group(this)'><span class='hide'>-1</span><span class='groupNm'>全部</span><span>["+total+"]</span></li>";
		str +="</ul>";
		$("#groupBox").html(str);
	}
}
function click_group(li){
	var groupName = $(li).find("span.groupNm").text();
	$.ajax({
		type:"post",
		url:"/dev/findDevListByGroupName.action",
		data:{groupName:groupName},
		success:function(r){
		    if (r.status=='ok') {
			showRoomTable(r.result);
		    }
		}
	});
	$("#page").css("display","none");
}
function showPage(){
	if(page<0){
	    return;
	}
	var uid=getSelUserid();
	$.ajax({
		type:"post",
		url:"/api/svc/devIndex.php",
		data:{fun:'findTesterListByUserId',userid:uid},
		success:function(r){
		    if (r.status=='ok') {
			showRoomTable(r.result);
			refreshData();
		    }
		}
	});
}
function click_page(obj){
	page = parseInt($(obj).text());
	pageSize = parseInt($("#pageSize").val());
	showPage();
}
function click_pageSize(){
	pageSize = $("#pageSize").val();
	getDevCount();
	showPage();
}
function getDevCount(){
	$.ajax({
		type:"post",
		url:"/dev/getDevCount.action",
		data:{pageSize:pageSize},
		success:function(response){
		    showPageList(response);
		}
	});
}
function showRoomTable(tb){//tb -- devId1:room1;devId2:room2;
	if(!tb){
	    $("#nova-room-table").html("");
	}else{
	    var rooms = tb;
	    var str = "";
	    for(var i=0;i<rooms.length;i++){
		var dev = rooms[i];
		var devId = dev.sn;
		var room = dev.name;
		str += "<div class=\"room roomOffline\">"
			+	"<div class=\"devId\">" + devId + "</div>" 
			+	"<div class=\"header\"  onclick='click_room(this)' title='房间:"+room+",设备号:"+devId+"'>" + room + "</div>"
			+"<div class='pm25' onclick='clk_data(this)'>"
			+	"<div class=\"value LED-font\" title=\"PM2.5\"> -- </div>"
			+	"<div class=\"timestamp\"> 0 </div>"
			+	"<div class=\"valueType\">	PM2.5 </div>"
			+"</div>"
			+ "<div class='margin'></div>"
			+"<div class='wendu' onclick='clk_data(this)'>"
			+ "<div class=\"value\" title=\"温度\"> -- </div>"
			+ "<div class=\"timestamp\"> 0 </div>"
			+ "<div class=\"valueType\">温度 </div>"
			+"</div>";
		str += "<div class='margin'></div>"
			+"<div class='shidu' onclick='clk_data(this)'>"
			+ "<div class=\"value\" title=\"湿度\"> -- </div>"
			+ "<div class=\"timestamp\"> 0 </div>"
			+ "<div class=\"valueType\">湿度</div>"
			+"</div>";
		str += "<div class='margin'></div>"
			+"<div class='co2' onclick='clk_data(this)'>"
			+ "<div class=\"value\" title=\"二氧化碳\"> -- </div>"
			+ "<div class=\"timestamp\"> 0 </div>"
			+ "<div class=\"valueType\">二氧化碳</div>"
			+"</div>";
		str += "<div class='margin'></div>"
			+"<div class='tvoc' onclick='clk_data(this)'>"
			+ "<div class=\"value\" title=\"异味指数\"> -- </div>"
			+ "<div class=\"timestamp\"> 0 </div>"
			+ "<div class=\"valueType\">异味指数</div>"
			+"</div>";
		str += "<div class='margin'></div>"
			+"<div class='jiaquan' onclick='clk_data(this)'>"
			+ "<div class=\"value\" title=\"甲醛\"> -- </div>"
			+ "<div class=\"timestamp\"> 0 </div>"
			+ "<div class=\"valueType\">甲醛</div>"
			+"</div>";
		str += "</div>";
	    }
	    $("#nova-room-table").html(str);
	    sortRoomTable("nova-room-table",1,true);
	    if(rooms.length>0 && rooms.length<ROOM_COL){
		    $("#nova-room-table").css("width",(120*rooms.length)+"px");
	    }else{
		    $("#nova-room-table").css("width",ROOM_WIDTH);
	    }
	    refreshShowType();
	}
}
function showPageList(devCount){
	var pageCnt = Math.ceil(devCount/pageSize);
	var str="<ul>";
	for(var i=1;i<=pageCnt;i++){
		str += "<li onclick=\"click_page(this)\">"+i+"</li>";
	}
	str += "<span>每页显示房间数:<input id=\"pageSize\" value=\""+pageSize+"\"/><input type=\"button\" onclick=\"click_pageSize()\" value=\"确定\"/></span></ul>";
	$("#pageList").html(str);
}
function swapRoom(rooms,i,j) 
{
    var html = $(rooms).eq(i).html();
    $(rooms).eq(i).html($(rooms).eq(j).html());
    $(rooms).eq(j).html(html);
}
function sortRoomTable(tbId, col, increase)
{
    var rooms = $("#"+tbId).children();
    var total = rooms.length;
    //外层循环，共要进行arr.length次求最大值操作
    for (var i = 0; i < total - 1; i++){
        var v = ($(rooms).eq(i).children().eq(col).text());
        //内层循环，找到第i大的元素，并将其和第i个元素交换
        for (var j = i+1; j < total; j++){
            var v2 = ($(rooms).eq(j).children().eq(col).text());
            if(increase){
            	if(v.localeCompare(v2)>0){
	                v = v2;
                    //交换两个元素的位置
                    swapRoom(rooms, i, j);
                }
            }else{
            	if(v.localeCompare(v2)<0){
	                v = v2;
                    //交换两个元素的位置
                    swapRow(tr, i, j);
                }
            }
        }
    }
}
function clk_type(li){
    $(li).find("input:checkbox").prop('checked',true);
    preventDefaultEvent(event);
}
function findSellerList(username){
    if (username) {
	$.ajax({
	    type:"post",
	    url:"/api/svc/userIndex.php",
	    data:{fun:'findUserListByFather',father:username},
	    success:function(r){
		if (r.status=='ok') {
		    showSellerList(r.result);
		}
	    }
	});
    }
}
function findConsumerList(username){
    if (username) {
	$.ajax({
	    type:"post",
	    url:"/api/svc/userIndex.php",
	    data:{fun:'findUserListByFather',father:username},
	    success:function(r){
		if (r.status=='ok') {
		    showConsumerList(r.result);
		}
	    }
	});
    }
}
function showSellerList(list){
    if (list) {
	var str="";
	str+="<li onclick='clk_seller(this)'><a href='javascript:void(0);'>";
	str+="<span class='hide' data='id'>"+userInfo.id+"</span>";
	str+="<span data='name'>"+userInfo.name+"</span> (";
	str+="<span data='province'>"+userInfo.province+"</span>-";
	str+="<span data='city'>"+userInfo.city+"</span>-";
	str+="<span data='county'>"+userInfo.county+"</span>)";
	str+="</a></li>";
	str+="<li class='divider'></li>";
	for(var i=0;i<list.length;i++){
	    var c = list[i];
	    if (c.role=='seller') {
		str+="<li onclick='clk_seller(this)'><a href='javascript:void(0);'>";
		str+="<span class='hide' data='id'>"+c.id+"</span>";
		str+="<span class='hide' data='role'>"+c.role+"</span>";
		str+="<span class='hide' data='areaId'>"+c.areaId+"</span>";
		str+="<span data='name'>"+c.name+"</span> (";
		str+="<span data='province'>"+c.province+"</span>-";
		str+="<span data='city'>"+c.city+"</span>-";
		str+="<span data='county'>"+c.county+"</span>)";
		str+="</a></li>";
	    }
	}
	$("#ul-seller-list").html(str);
    }
}
function showConsumerList(list){
    if (list) {
	var str="";
	for(var i=0;i<list.length;i++){
	    var c = list[i];
	    if (c.role=='consumer') {
		str+="<li onclick='clk_consumer(this)'><a href='javascript:void(0);'>";
		str+="<span class='hide' data='id'>"+c.id+"</span>";
		str+="<span class='hide' data='role'>"+c.role+"</span>";
		str+="<span class='hide' data='areaId'>"+c.areaId+"</span>";
		str+="<span data='name'>"+c.name+"</span> (";
		str+="<span data='province'>"+c.province+"</span>-";
		str+="<span data='city'>"+c.city+"</span>-";
		str+="<span data='county'>"+c.county+"</span>)";
		str+="</a></li>";
	    }
	}
	$("#ul-consumer-list").html(str);
    }
}
function clk_seller(li) {
    var cname=$(li).find("span[data='name']").text();
    var cid = $(li).find("span[data='id']").text();
    $("#seller-list span[data='value']").text(cid);
    $("#seller-list span[data='show']").text(cname);
    $("#consumer-list span[data='value']").text("");
    $("#consumer-list span[data='show']").text("选择用户");
    findConsumerList(cname);
    showPage();
}
function clk_consumer(li) {
    var cname=$(li).find("span[data='name']").text();
    var cid = $(li).find("span[data='id']").text();
    $("#consumer-list span[data='value']").text(cid);
    $("#consumer-list span[data='show']").text(cname);
    showPage();
}
function refreshShowType(){
    $("#list-showtype button").each(function(){
	if ($(this).hasClass('btn-primary')) {
	    $("div."+$(this).attr('data')).show();
	    $("div."+$(this).attr('data')+"in").show();
	    $("div."+$(this).attr('data')+"out").show();
	    $("div."+$(this).attr('data')+"1").show();
	    $("div."+$(this).attr('data')+"2").show();
	    $("div."+$(this).attr('data')+"3").show();
	    $("div."+$(this).attr('data')+"4").show();
	    $("div."+$(this).attr('data')).prev("div.margin").show();
	}else{
	    $("div."+$(this).attr('data')).hide();
	    $("div."+$(this).attr('data')+"in").hide();
	    $("div."+$(this).attr('data')+"out").hide();
	    $("div."+$(this).attr('data')+"1").hide();
	    $("div."+$(this).attr('data')+"2").hide();
	    $("div."+$(this).attr('data')+"3").hide();
	    $("div."+$(this).attr('data')+"4").hide();
	    $("div."+$(this).attr('data')).prev("div.margin").hide();
	}
    });
}
function getSelUserid(){
    var cid = $("#consumer-list span[data='value']").text();
    if (cid) {
	return cid;
    }else{
	cid=$("#seller-list span[data='value']").text();
	if (cid) {
	    return cid;
	}else{
	    return logginInfo.userid;
	}
    }
}
function getSelUsername(){
    var cid = $("#consumer-list span[data='value']").text();
    var nm;
    if (cid) {
	nm=$("#consumer-list span[data='show']").text()
	return nm;
    }else{
	cid=$("#seller-list span[data='value']").text();
	if (cid) {
	    nm=$("#seller-list span[data='show']").text()
	    return nm;
	}else{
	    return logginInfo.username;
	}
    }
}
function clk_datagrid(btn){
    var type=$("#list-showtype button.btn-primary:first").attr("data");
    var uid = getSelUserid();
    window.open("/data.html?uid="+uid+"&type="+type);
}
function clk_plot(btn){
    var type=$("#list-showtype button.btn-primary:first").attr("data");
    var uid = getSelUserid();
    window.open("/plot.html?uid="+uid+"&type="+type);
}